// import { DownOutlined, PlusOutlined } from '@ant-design/icons';
import AuthComponent from '@/components/Authorized/AuthComponent';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import {
  Button,
  message,
  DatePicker,
  Radio,
  Input,
  Select,
} from 'antd';
import React, { useState, useCallback, useRef, useEffect } from 'react';
import ProTable from '@ant-design/pro-table';
import { useRequest } from '@umijs/hooks';
import { irregularluggagedetailTable, downloadluggagedetailExcel, queryCityInfo } from '../service';
import moment from 'moment';
import styles from './index.less';
const { Option } = Select;

const TableList = (props) => {
  const { data: selectData } = useRequest(queryCityInfo);
  const [createModalVisible, handleModalVisible] = useState(false);
  const [exportFlag, handleExportFlag] = useState('')
  const actionRef = useRef();
  const ref = useRef();
  const searchRef = useRef();

  const reloadTable = useCallback(function reloadData() {
    if (searchRef.current) {
      searchRef.current.click();
    }
  }, []);

  const [height, controlH] = useState(300);
  const [isCollapse, controlC] = useState(true);
  useEffect(() => {
    if (isCollapse) {
      controlH(document.body.clientHeight - 360);
    } else {
      controlH(document.body.clientHeight - 470);
    }
  }, [isCollapse])
  const columns = [
   {
    title: '航班日期',
    dataIndex: 'flightDate',
    width: 100,
    hideInSearch: true
    },
    {
      title: '航班号',
      dataIndex: 'flightNumber',
      width: 100,
      hideInSearch: true
    },
    {
      title: '航班开始日期',
      hideInTable: true,
      dataIndex: 'startDate',
      order: 7,
      renderFormItem: (_, { ...rest }) => {
        const format = 'YYYY-MM-DD';
        return (
          <DatePicker
            style={{width: '100%'}}
            format={format}
            {...rest}
          />
        );
      },
    },
    {
      title: '航班结束日期',
      hideInTable: true,
      order:6,
      dataIndex: 'endDate',
      renderFormItem: (_, { ...rest }) => {
        const format = 'YYYY-MM-DD';
        return (
          <DatePicker
            style={{width: '100%'}}
            format={format}
            {...rest}
          />
        );
      },
    },
    {
      // 多个查询选项
      title: '起飞航站',
      dataIndex: 'org',
      width: 100,
      initialValue: '', //缺个默认接口服务航站
      renderFormItem: (_, { ...rest }, form) => {
        return (
          <Select
            allowClear={true}
            showSearch
            placeholder="请选择"
            defaultActiveFirstOption={false}
            showArrow={false}
            filterOption={true}
            optionFilterProp="children"
            notFoundContent={null}
            {...rest}
          >
            {selectData &&
              selectData.map((v, i) => {
                return (
                  <Option key={v.CITY3CODE}>{v.CITYNAME}-{v.CITY3CODE}</Option>
                )
              })
            }
          </Select>
        );
      },
    },
    {
      // 多个查询选项
      title: '到达航站',
      dataIndex: 'dst',
      width: 100,
      initialValue: '', //缺个默认接口服务航站
      renderFormItem: (_, { ...rest }, form) => {
        return (
          <Select
            allowClear={true}
            showSearch
            placeholder="请选择"
            defaultActiveFirstOption={false}
            showArrow={false}
            filterOption={true}
            optionFilterProp="children"
            notFoundContent={null}
            {...rest}
          >
            {selectData &&
              selectData.map((v, i) => {
                return (
                  <Option key={v.CITY3CODE}>{v.CITYNAME}-{v.CITY3CODE}</Option>
                )
              })
            }
          </Select>
        );
      },
    },
    {
      // 多个查询选项
      title: '处理航站',
      key:'terminalCode',
      // hideInTable: true,
      dataIndex: 'terminalCode',
      width: 100,
      initialValue: '', //缺个默认接口服务航站
      renderFormItem: (_, { ...rest }, form) => {
        return (
          <Select
            allowClear={true}
            showSearch
            placeholder="请选择"
            defaultActiveFirstOption={false}
            showArrow={false}
            filterOption={true}
            optionFilterProp="children"
            notFoundContent={null}
            {...rest}
          >
            {selectData &&
              selectData.map((v, i) => {
                return (
                  <Option key={v.CITY3CODE}>{v.CITYNAME}-{v.CITY3CODE}</Option>
                )
              })
            }
          </Select>
        );
      },
    },
    {
      title: '补偿类型',
      key: 'accidentType',
      initialValue: '',
      dataIndex: 'accidentType',
      width: 100,
      filters: [
        {text: '破损', value: '1'},
        {text: '少收',value: '2'},
        {text: '箱包', value: '3'},
        {text: '内件缺失', value: '4'},

      ],
      valueEnum: {
        '1': '破损',
        '2': '少收',
        '3': '箱包',
        '4': '内件缺失',

      },
    },
    {
      title: '地区类型',
      key: 'dOrI',
      dataIndex: 'dOrI',
      width:120,
      filters: [
        {text: '国内', value: 'D'},
        {text: '国际', value: 'I'}
      ],
      valueEnum: {
        'D': '国内',
        'I':'国际'
      },
    },
    {
      title: '旅客姓名',
      dataIndex: 'passengerName',
      width: 100,
    },
    {
      title: '票号',
      dataIndex: 'ticketNumber',
      width: 100,
    },
    {
      title: '补偿单号',
      hideInSearch: true,
      dataIndex: 'orderId',
      width: 100,
    },
    {
      title: '事故单号',
      hideInSearch: true,
      dataIndex: 'accidentId',
      width: 100,
    },
    {
      title: '行李编号',
      hideInSearch: true,
      dataIndex: 'pkgNumber',
      width: 100,
    },
    {
      title: '机号',
      hideInSearch: true,
      dataIndex: 'planeCode',
      width: 100,
    },
    {
      title: '机型',
      hideInSearch: true,
      dataIndex: 'flightModel',
      width: 90,
    },
    {
      title: '机型',
      dataIndex: 'planeType',
      hideInTable:true,
      key: 'planeType',
      renderFormItem: (_, { ...rest }, form) => {
        return (
          <Select
            mode="multiple"
            allowClear={true}
            placeholder="请选择"
          >
            <Option key='A319'>A319</Option>
            <Option key='A320'>A320</Option>
            <Option key='A321'>A321</Option>
            <Option key='A330'>A330</Option>
            <Option key='A350'>A350</Option>
          </Select>
        );
      },
    },
    {
      title: '重量',
      hideInSearch: true,
      dataIndex: 'littlePkgWeight',
      width: 100,
    },
    {
      title: '补偿金额',
      hideInSearch: true,
      dataIndex: 'compensateAmount',
      width: 100,
    },
    {
      title: '领取渠道',
      hideInSearch: true,
      dataIndex: 'applyWay',
      width: 100,
    }
  ];
  const [inited, setInited] = useState(false);
  const [firstLoadDate, setFirstLoadDate] = useState(true);
  useEffect(() => {
    if (actionRef.current && inited) {
       reloadTable();
    } else {
      setInited(true);
    }
  }, [inited]);

  // 获取列表详情方法
  const beforeSearchSubmit = useCallback(params => {

    params['startDate'] = params.startDate ? params.startDate.format('YYYY-MM-DD') : '';
    params['endDate'] = params.endDate ? params.endDate.format('YYYY-MM-DD') : '';

    if (!isCollapse) {
      return { ...params }
    } else {
      if (event&&event.target&&event.target.querySelector&&event.target.querySelector('span') && event.target.querySelector('span').innerText === '查 询') {
        if (Object.keys(params).indexOf('startDate') === -1) {
          params.startDate = ''
        }
        if (Object.keys(params).indexOf('endDate') === -1) {
          params.endDate = ''
        }
      } else if (event&&event.target&&event.target.querySelector&&event.target.querySelector('span') && event.target.querySelector('span').innerText === '重 置') {
        ref.current.setFieldsValue({
          startDate: moment(),
          endDate: moment()
        })
      }
      return { ...params }
    }
  }, []);

  const [selectedRowKeys, handleSelectedRowKeys] = useState([]) // 勾选索引
  const [selectedRows, handleSelectedRows] = useState([]) // 勾选列
  const [searchParams, handleSearchParams] = useState() // 存储搜索条件
  // 选中添加值
  const tableSelectChange = (selectedRowKeys, selectedRows) => {
    handleSelectedRowKeys(selectedRowKeys);
    handleSelectedRows(selectedRows);
  };
  // 设置选中的值
  const rowSelection = {
    selectedRowKeys,
    onChange: tableSelectChange,
  };
  //导出方法
  const handleExport = () => {
    if (!exportFlag){
      message.error('表格数据为空')
      return false
    }
    const hide = message.loading('正在导出');
    let res = downloadluggagedetailExcel(searchParams)
      .then(res => {
        let blob = new Blob([res], {
          type:
            'application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        });
        let elink = document.createElement('a');
        let time=moment(Date.now()).format('YYYY-MM-DD HH_ss_mm')
        elink.download = '异常行李补偿明细表'+time+'.xls'
        elink.style.display = 'none';
        elink.href = URL.createObjectURL(blob);
        document.body.appendChild(elink);
        elink.click();
        document.body.removeChild(elink);
        hide();
        message.success('导出成功');
      })
      .catch(err => {
        console.log(err);
      });
  };

  return (
    <>
      <ProTable
        options={{density: false,fullScreen:true, reload:false, setting:true}}
        actionRef={actionRef}
        formRef={ref}
        dateFormatter="YYYY-MM-DD"
        scroll={{ x: 1100, y: height }}
        size='small'
        className={`${styles.luggageCharts} rest-pro-table-form-compact rest-pro-table-tab ${isCollapse?'':'collapse'}`}
        search={{
          searchText: (
            <span ref={searchRef} href>
              查询
            </span>
          ),
          onCollapse: val => {
            controlC(val);
          }
        }}
        toolBarRender={() => [
          <AuthComponent authCode="luggageCharts.compensationlist.export">
             <Button icon="download" type="primary" onClick={handleExport} selectedKeys={[]} style={{ padding: '0px 0px 0px 8px',width:'73px' }}>
              导出           
            </Button>
          </AuthComponent>
        ]}
        headerTitle={
          <div>
            <span style={{ paddingRight: 10, fontWeight: "bold", color: "#000" }}>补偿明细表</span>
          </div>
        }
        beforeSearchSubmit={beforeSearchSubmit}
        request={params => {
          if (!params['startDate'] && !params['endState']) {
            params['startDate'] = moment().format('YYYY-MM-DD');
            params['endDate'] = moment().format('YYYY-MM-DD');
            ref.current.setFieldsValue({
              startDate: moment(),
              endDate: moment()
            })
          }
          params.planeType = params.planeType && params.planeType.join(',')

          handleSearchParams(params);
          return irregularluggagedetailTable(params);
        }}

        postData={data => {
          if (data.length === 0) {
            handleExportFlag(false)
          } else {
            handleExportFlag(true)
          }
          return data
        }}
        columns={columns}
        rowKey="id"
        pagination={{
          showSizeChanger: true,
          showTotal: (total, range) => `${range[0]}-${range[1]} 共 ${total} 项`
        }}
      />
    </>
  );
};

export default Form.create()(TableList);
